package cn.doitedu.rtmk.mgmt.doit39_rtmk_management.dao;

import cn.doitedu.rtmk.mgmt.doit39_rtmk_management.pojo.Person;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public class PersonDao {
    Connection connection;

    public PersonDao() throws SQLException {
        connection = DriverManager.getConnection("jdbc:mysql://doitedu:3306/doit39", "root", "root");
    }

    public List<Person> selectPersonByName(String name) throws SQLException {
        PreparedStatement pst = connection.prepareStatement("select name,age,gender,job from person where name = ?");
        pst.setString(1, name);

        ArrayList<Person> personList = new ArrayList<>();

        ResultSet resultSet = pst.executeQuery();
        while (resultSet.next()) {
            String pname = resultSet.getString("name");
            int age = resultSet.getInt("age");
            String gender = resultSet.getString("gender");
            String job = resultSet.getString("job");

            Person person = new Person(pname, age, gender, job);
            personList.add(person);

        }

        return personList;
    }

    public int insertPerson(Person person) throws SQLException {

        PreparedStatement pst = connection.prepareStatement("insert into person values (?,?,?,?)");
        pst.setString(1, person.getName());
        pst.setInt(2, person.getAge());
        pst.setString(3, person.getGender());
        pst.setString(4, person.getJob());

        boolean res = pst.execute();

        return res ? 0 : 1;
    }

    public int updatePerson(Person person) throws SQLException {

        PreparedStatement pst = connection.prepareStatement("update person set age =? ,gender =? ,job=? where name =?");
        pst.setInt(1, person.getAge());
        pst.setString(2, person.getGender());
        pst.setString(3, person.getJob());
        pst.setString(4, person.getName());

        boolean res = pst.execute();

        return res ? 0 : 1;
    }





}
